package com.example.java.window;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.util.Random;

/**
 * 翻滚窗口：窗口不重叠
 * 1、基于时间驱动
 * 2、基于事件驱动
 */
public class TumblingWindow {
    static StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

    public static void main(String[] args) throws Exception {
       testCountWindow();
//        testTimeWindow();

    }


    private static void testCountWindow() throws Exception {
        DataStreamSource<String> data = env.socketTextStream("linux121", 8888);
        SingleOutputStreamOperator<Tuple2<String, Integer>> mapStream = data
                .map(new MapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> map(String value) throws Exception {
                        int random = new Random().nextInt(10);
                        return new Tuple2<String, Integer>(value, random);
                    }
                });
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = mapStream.keyBy(value -> value.f0);
        // 基于事件驱动, 每相隔3个事件(即三个相同key的数据), 划分一个窗口进行计算
        WindowedStream<Tuple2<String, Integer>, String, GlobalWindow> countWindow = keyedStream.countWindow(3);
        // apply是窗口的应用函数，即apply里的函数将应用在此窗口的数据上。
        countWindow.apply(new MyCountWindowFunction()).print();
        env.execute();
    }

    private static void testTimeWindow() throws Exception {
        DataStreamSource<Boolean> data = env.addSource(new SourceFunction<Boolean>() {
            @Override
            public void run(SourceContext<Boolean> ctx) throws Exception {
                Random random = new Random();
                while (true) {
                    ctx.collect(random.nextBoolean());
                    Thread.sleep(500);
                }
            }

            @Override
            public void cancel() {

            }
        });

        SingleOutputStreamOperator<Tuple2<Boolean, Integer>> mapped = data.map(new MapFunction<Boolean, Tuple2<Boolean, Integer>>() {
            @Override
            public Tuple2<Boolean, Integer> map(Boolean value) throws Exception {
                Random random = new Random();
                return new Tuple2<Boolean, Integer>(value, random.nextInt(10));

            }
        });
        KeyedStream<Tuple2<Boolean, Integer>, Boolean> keyedStream = mapped.keyBy(value -> value.f0);

        // 基于时间驱动，每隔5s划分一个窗口
        WindowedStream<Tuple2<Boolean, Integer>, Boolean, TimeWindow> timeWindow = keyedStream.timeWindow(Time.seconds(5));
        // apply是窗口的应用函数，即apply里的函数将应用在此窗口的数据上。
        SingleOutputStreamOperator<String> applied = timeWindow.apply(new MyTimeWindowFunction());
        applied.print();
        env.execute();

    }
}

class MyTimeWindowFunction implements WindowFunction<Tuple2<Boolean, Integer>, String, Boolean, TimeWindow> {

    @Override
    public void apply(Boolean key, TimeWindow window, Iterable<Tuple2<Boolean, Integer>> input, Collector<String> out) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        StringBuffer sb = new StringBuffer();
        for (Tuple2<Boolean, Integer> tuple2 : input) {
            sb.append(tuple2.f1 + ",");
        }
        out.collect("key:" + key + " value: " + sb + "| window_start :"
                + format.format(window.getStart()) + "  window_end :" + format.format(window.getEnd())
        );

    }
}

class MyCountWindowFunction implements WindowFunction<Tuple2<String, Integer>, String, String, GlobalWindow> {

    @Override
    public void apply(String key, GlobalWindow window, Iterable<Tuple2<String, Integer>> input, Collector<String> out) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

        int sum = 0;

        for (Tuple2<String, Integer> tmp : input) {
            sum += tmp.f1;
        }
        // 无用的时间戳，默认值为： Long.MAX_VALUE,因为基于事件计数的情况下，不关心时间。
        long maxTimestamp = window.maxTimestamp();

        out.collect("key:" + key + " value: " + sum + "| maxTimeStamp :"
                + maxTimestamp + "," + format.format(maxTimestamp)
        );
    }
}
